﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AppManagement.BusManagers
{
    #region Using
    using DevComponents.DotNetBar;
    using AppManagement.Helpers;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.UsersManager;
    #endregion

    /// <summary>
    ///  manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyNhanVien: Office2007Form
    {
        //  event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        public string Criteria_MaBacSi { get; set; }
        public string Criteria_Ho { get; set; }
        public string Criteria_Ten { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaLoaiNhanVien;

        // ---------------- E -----------------

        public FrmQuanLyNhanVien(bool EnableBtnChon = false)
        {
            InitializeComponent();
            InitHiddenFields();
            btnChon.Enabled = EnableBtnChon;
        }

        public FrmQuanLyNhanVien(string mabacsi, string ho, string ten)
        {
            InitializeComponent();
            InitHiddenFields();
            btnChon.Enabled = false;

            Criteria_MaBacSi = mabacsi;
            Criteria_Ho = ho;
            Criteria_Ten = ten;
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaLoaiNhanVien = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaLoaiNhanVien",
                Text = ""
            };
            txtMaLoaiNhanVien.Visible = false;
        }

        private void FrmQuanLyNhanVien_Load(object sender, EventArgs e)
        {
            if (Criteria_MaBacSi == null)
            {
                LoadData();
            }
            else
            {
                Search();
            }
        }

        public void Search()
        {
            var lstItem = BacSi_NhanVienRepository.Search(Criteria_MaBacSi, Criteria_Ho, Criteria_Ten);

            var dt = new DataTable();
            dt.Columns.Add("MaBSNV");
            dt.Columns.Add("HoTen");
            dt.Columns.Add("LoaiNguoiDung");
            dt.Columns.Add("GioiTinh");
            dt.Columns.Add("DTDD");
            dt.Columns.Add("Email");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaBSNV, lstItem[i].ToString(), lstItem[i].LoaiNguoiDung.TenLoaiNguoiDung, lstItem[i].GioiTinh == null ? "" : (lstItem[i].GioiTinh == true ? "Nam" : "Nữ"), lstItem[i].DTDD, lstItem[i].Email);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                LoadData();
                EraseTextboxes();
                MessageBox.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    LoadData();
                    EraseTextboxes();
                    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                LoadData();
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            EraseTextboxes();
        }

        private void dtgvDataList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            txtMaNhanVien.Text = dtgvDataList.SelectedRows[0].Cells["MaBSNV"].Value.ToString(); ;

            var item = BacSi_NhanVienRepository.SelectByID(txtMaNhanVien.Text);
            LoadDetailInfo(item);
        }

        public void LoadDetailInfo(BacSi_NhanVien item)
        {
            txtHo.Text = item.Ho == null ? "" : item.Ho;
            txtTen.Text = item.Ten == null ? "" : item.Ten;
            txtNoiSinh.Text = item.NoiSinh == null ? "" : item.NoiSinh;
            txtNoiOHienTai.Text = item.NoiOHienTai == null ? "" : item.NoiOHienTai;
            txtChuyenMon.Text = item.ChuyenMon == null ? "" : item.ChuyenMon;
            txtDTDD.Text = item.DTDD == null ? "" : item.DTDD;
            txtDienThoaiNha.Text = item.DTNha == null ? "" : item.DTNha;
            txtMaLoaiNhanVien.Text = item.MaLoaiNguoiDung == null ? "" : item.MaLoaiNguoiDung.ToString();
            txtLoaiNhanVien.Text = item.MaLoaiNguoiDung == null ? "" : item.LoaiNguoiDung.TenLoaiNguoiDung;
            dtNgaySinh.Value = item.NgaySinh == null ? DateTime.MinValue : item.NgaySinh.Value;
            dtNgayVaoLam.Value = item.NgayVaoLam == null ? DateTime.MinValue : item.NgayVaoLam.Value;
            cbxGioiTinh.SelectedIndex = item.GioiTinh == null ? -1 : (item.GioiTinh.Value ? 0 : 1);
            txtEmail.Text = item.Email == null ? "" : item.Email;
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = txtMaNhanVien.Text;
            var nhanvien = BacSi_NhanVienRepository.SelectByID(id);
            TransferDataInfo(this, new TransferSimpleDataEvent(id + "#" + nhanvien.ToString()));
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadBacSi()
        {
            var lstItem = BacSi_NhanVienRepository.SelectBacSis();

            var dt = new DataTable();
            dt.Columns.Add("MaBSNV");
            dt.Columns.Add("HoTen");
            dt.Columns.Add("LoaiNguoiDung");
            dt.Columns.Add("GioiTinh");
            dt.Columns.Add("DTDD");
            dt.Columns.Add("Email");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaBSNV, lstItem[i].ToString(), lstItem[i].LoaiNguoiDung.TenLoaiNguoiDung, lstItem[i].GioiTinh == null ? "" : (lstItem[i].GioiTinh == true ? "Nam" : "Nữ"), lstItem[i].DTDD, lstItem[i].Email);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = BacSi_NhanVienRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaBSNV");
            dt.Columns.Add("HoTen");
            dt.Columns.Add("LoaiNguoiDung");
            dt.Columns.Add("GioiTinh");
            dt.Columns.Add("DTDD");
            dt.Columns.Add("Email");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaBSNV, lstItem[i].ToString() , lstItem[i].LoaiNguoiDung.TenLoaiNguoiDung, lstItem[i].GioiTinh == null ? "" : (lstItem[i].GioiTinh == true ? "Nam" : "Nữ"), lstItem[i].DTDD, lstItem[i].Email);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaNhanVien is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE || mode == EnumUpdateMode.CHOOSING)
            {
                if (txtMaNhanVien.Text == "")
                {
                    errorText = "Vui lòng chọn nhân viên";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtHo.Text == "")
                {
                    errorText = "Vui lòng nhập họ nhân viên";
                    return false;
                }
                if (txtTen.Text == "")
                {
                    errorText = "Vui lòng nhập tên nhân viên";
                    return false;
                }
                if (txtMaLoaiNhanVien.Text == "")
                {
                    errorText = "Vui lòng chọn loại nhân viên";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new BacSi_NhanVien
                {
                    MaBSNV = txtMaNhanVien.Text,
                    MaLoaiNguoiDung = int.Parse(txtMaLoaiNhanVien.Text),
                    Ho = txtHo.Text,
                    Ten = txtTen.Text,
                    NoiSinh = txtNoiSinh.Text,
                    NoiOHienTai = txtNoiOHienTai.Text,
                    ChuyenMon = txtChuyenMon.Text,
                    DTDD = txtDTDD.Text,
                    DTNha = txtDienThoaiNha.Text,
                    Email = txtEmail.Text,
                    GioiTinh = cbxGioiTinh.SelectedIndex == 0 ? true : false
                };

                UpdateForeignKeys(item);

                if (!BacSi_NhanVienRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtMaNhanVien.Text = "";
            txtHo.Text = "";
            txtTen.Text = "";
            txtNoiSinh.Text = "";
            txtNoiOHienTai.Text = "";
            txtChuyenMon.Text = "";
            txtDTDD.Text = "";
            txtDienThoaiNha.Text = "";
            txtMaLoaiNhanVien.Text = "";
            txtLoaiNhanVien.Text = "";
            txtEmail.Text = "";
            cbxGioiTinh.SelectedIndex = -1;
            dtNgaySinh.Value = DateTime.MinValue;
            dtNgayVaoLam.Value = DateTime.MinValue;
            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = BacSi_NhanVienRepository.SelectByID(txtMaNhanVien.Text);
                item.MaLoaiNguoiDung = int.Parse(txtMaLoaiNhanVien.Text);
                item.Ho = txtHo.Text;
                item.Ten = txtTen.Text;
                item.NoiSinh = txtNoiSinh.Text;
                item.NoiOHienTai = txtNoiOHienTai.Text;
                item.ChuyenMon = txtChuyenMon.Text;
                item.DTDD = txtDTDD.Text;
                item.DTNha = txtDienThoaiNha.Text;
                item.Email = txtEmail.Text;
                item.GioiTinh = cbxGioiTinh.SelectedIndex == 0 ? true : false;

                UpdateForeignKeys(item);

                return BacSi_NhanVienRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        public void UpdateForeignKeys(BacSi_NhanVien item)
        {
            if (dtNgaySinh.Value != DateTime.MinValue)
            {
                item.NgaySinh = dtNgaySinh.Value;
            }
            if (dtNgayVaoLam.Value != DateTime.MinValue)
            {
                item.NgayVaoLam = dtNgayVaoLam.Value;
            }
            if (txtMaLoaiNhanVien.Text != "")
            {
                item.MaLoaiNguoiDung = int.Parse(txtMaLoaiNhanVien.Text);
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return BacSi_NhanVienRepository.Delete(txtMaNhanVien.Text);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        private void btnChonLoaiNhanVien_Click(object sender, EventArgs e)
        {
            FrmQuanLyLoaiNguoiDung frm = new FrmQuanLyLoaiNguoiDung(true);
            frm.Handler += GetLoaiNhanVien;
            frm.ShowDialog();
        }

        public void GetLoaiNhanVien(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaLoaiNhanVien.Text = comp[0];
            txtLoaiNhanVien.Text = comp[1];
        }
    }
}